﻿using NetworkPower.DataModel.Models;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace NetworkPower.UI
{
    /// <summary>
    /// Interaction logic for ReplaceBlueprint.xaml
    /// </summary>
    public partial class ReplaceBlueprint : Window
    {

        static NetworkPowerContext context = new NetworkPowerContext();
        private Project project = null;
        private string currentFolder;

        public ReplaceBlueprint(Project project)
        {

            InitializeComponent();
            this.project = project;
            txtProject.Text = project.ProjectName;
            BindVoltage();
            currentFolder = Directory.GetCurrentDirectory();
        }

        private Voltage CurrentVoltage
        {
            get { return cmbVoltage.SelectedItem as Voltage; }
        }

        private SeperatorType CurrentSeperatorType
        {
            get { return cmbSepType.SelectedItem as SeperatorType; }
        }

        private Unit CurrentUnit
        {
            get { return cmbSepName.SelectedItem as Unit; }
        }

        private void BindVoltage()
        {
            var datasource = context.Voltages.Where(v => v.ProjectID == project.ProjectID).OrderBy(v => v.VoltageValue).ToList();
            cmbVoltage.ItemsSource = datasource;

        }

        private void cmbVoltage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            cmbSepType.ItemsSource = null;
            var selectedVoltage = cmbVoltage.SelectedItem as Voltage;
            var datasource = context.SeperatorTypes.Where(s => s.VoltageID == selectedVoltage.VoltageID).OrderBy(s => s.SeperatorValue).ToList();
            cmbSepType.ItemsSource = datasource;

            lvPaper.Items.Clear();
            var path = currentFolder + @"\" + selectedVoltage.VoltageValue;

            string[] files = Directory.GetFiles(path);
            foreach (string file in files)
            {
                string fileName = System.IO.Path.GetFileName(file);
                if (System.IO.Path.GetExtension(fileName).Equals(".dxf"))
                {
                    lvPaper.Items.Add(fileName);
                }
            }
        }

        private void cmbSepType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            cmbSepName.ItemsSource = null;
            //var selectedVoltage = cmbVoltage.SelectedItem as Voltage;
            if (cmbSepType.SelectedIndex >= 0)
            {
                var selectedSepType = cmbSepType.SelectedItem as SeperatorType;

                var datasource = context.Units.Where(s => s.SeperatorTypeID == selectedSepType.SeperatorTypeID).ToList();
                cmbSepName.ItemsSource = datasource;
            }

        }

        private void btnPath_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            var rs = fbd.ShowDialog();
            if (rs == System.Windows.Forms.DialogResult.OK)
            {
                var path = fbd.SelectedPath;
                tbPath.Text = path;
            }
        }

        private void ExChangeNo(string file, List<Tuple<string, string, string>> list)
        {
            try
            {
                string fileName = System.IO.Path.GetFileName(file);
                if (System.IO.Path.GetExtension(fileName).Equals(".dxf"))
                {
                    var backpath = currentFolder + @"\" + CurrentVoltage.VoltageValue + @"\" + fileName + ".bak";
                    var fullpath = currentFolder + @"\" + CurrentVoltage.VoltageValue + @"\" + fileName;
                    string text = File.ReadAllText(fullpath, Encoding.Default);
                    //string pattern = @"\btest\b";
                    string result = string.Empty;
                    foreach (var tuple in list)
                    {
                        if (tuple.Item2.Length != 0 && tuple.Item3.Length != 0)
                        {
                            string pattern = @"\b" + tuple.Item2 + @"\b";
                            result = Regex.Replace(text, pattern, tuple.Item3);
                            text = result;//text.Replace(tuple.Item2, tuple.Item3);
                        }
                    }

                    File.Copy(fullpath, backpath, true);
                    File.WriteAllText(fullpath, text, Encoding.Default);
                    File.Copy(fullpath, tbPath.Text + @"\" + fileName, true);
                    System.Windows.MessageBox.Show("OK");
                }
            }
            catch (Exception)
            {


                throw;
            }

        }


        private List<LoopLine> GetLoopLineList(string name)
        {
            var sumlist = new List<LoopLine>();
            var devicelist = context.Devices.Where(o => o.DeviceName.ToUpper() == name.ToUpper()).ToList();
            string looplines = "";
            foreach (var device in devicelist)
            {

                looplines = device.LoopLineIds;
                var array = looplines.Split(',');
                for (int i = 0; i < array.Length; i++)
                {
                    Guid id = Guid.Parse(array[i]);
                    var loopline = context.LoopLines.Single(o => o.LoopLineId == id);
                    sumlist.Add(loopline);
                }

            }
            return sumlist;
        }

        private List<LoopLine> GetSubLoopLineList(List<LoopLine> list)
        {
            var result = new List<LoopLine>();
            var filter = context.LoopLines.Where(o => o.VoltageId == CurrentVoltage.VoltageID && o.SeperatorTypeId == CurrentSeperatorType.SeperatorTypeID &&
            o.UnitId == CurrentUnit.UnitID.ToString() && o.IsTitle == false);

            foreach (var loopline in list)
            {
                foreach (var item in filter)
                {
                    if (item.FullTerminalNo.Contains(loopline.TerminalNo))
                    {
                        result.Add(item);
                    }
                }
            }

            return result;
        }

        private string GetCirNo(List<LoopLine> list, string excelCirlNo, string excelOrignal)
        {


            if (excelOrignal.Contains("~"))
            {
                //1 vs n
                var result = string.Empty;
                if (list.Count(o => o.CircuitNo == excelCirlNo) != 0)
                {
                    var fatherNo = list.FirstOrDefault(o => o.CircuitNo == excelCirlNo).FatheTerminalNo;
                    string minTerminalNo = list.Where(o => o.CircuitNo == excelCirlNo).Min(o => o.TerminalNo).ToString();
                    string maxTerminalNo = list.Where(o => o.CircuitNo == excelCirlNo).Max(o => o.TerminalNo).ToString();
                    result = fatherNo + minTerminalNo + "~" + maxTerminalNo;

                }

                return result;
            }
            else
            {
                if (list.Count(o => o.CircuitNo == excelCirlNo) == 0)
                {
                    return string.Empty;
                }
                else
                {
                    return list.FirstOrDefault(o => o.CircuitNo == excelCirlNo).FullTerminalNo;
                }
            }
        }



        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            //var xxx = GetFullTerminalNo("");

            if (lvPaper.SelectedItems.Count != 0)
            {
                var numbers = context.LoopLines;
                IWorkbook wk = null;

                var selectedVoltage = cmbVoltage.SelectedItem as Voltage;
                var path = currentFolder + @"\" + selectedVoltage.VoltageValue;
                wk = GetWorkBook(path + @"\" + selectedVoltage.VoltageValue + @".xlsx");
                var targetNo = string.Empty;
                var list = new List<string>();
                List<Tuple<string, string, string>> tripleList = new List<Tuple<string, string, string>>();
                var septName = cmbSepName.Text;
                foreach (var p in lvPaper.SelectedItems)
                {
                    for (int i = 0; i < wk.NumberOfSheets; i++)
                    {
                        if (wk.GetSheetAt(i).SheetName.ToLower() == p.ToString().ToLower())
                        {

                            var sheet = wk.GetSheetAt(i);
                            IRow row = sheet.GetRow(0);
                            for (int j = 0; j < sheet.LastRowNum; j++)
                            {
                                //j++;
                                row = sheet.GetRow(j + 1);

                                if (row != null)// && row.GetCell(3).ToString().ToLower() != septName.ToLower())
                                {
                                    var curNo = row.GetCell(0).ToString();
                                    targetNo = row.GetCell(1).ToString();
                                    var deviceName = row.GetCell(2).ToString();
                                    var deviceLoopLines = GetLoopLineList(deviceName);
                                    var subLoopLines = GetSubLoopLineList(deviceLoopLines);
                                    var replaceNo = GetCirNo(subLoopLines, curNo, targetNo);
                                    if (!string.IsNullOrEmpty(replaceNo))
                                    {
                                        tripleList.Add(new Tuple<string, string, string>(curNo, targetNo, replaceNo));
                                    }

                                    //var curNo = row.GetCell(0).ToString();
                                    //targetNo = row.GetCell(1).ToString();
                                    //var replaceNo = numbers.SingleOrDefault(o => o.CircuitNo == curNo).TerminalNo;
                                    //tripleList.Add(new Tuple<string, string, string>(curNo, targetNo, replaceNo));
                                }

                            }
                            ExChangeNo(path + @"\" + sheet.SheetName, tripleList);
                        }



                    }


                }
            }
        }



        public IWorkbook GetWorkBook(string filePath)
        {
            IWorkbook wk = null;
            string extension = System.IO.Path.GetExtension(filePath);
            using (FileStream fs = File.OpenRead(filePath))
            {
                if (extension.Equals(".xls"))
                {
                    wk = new HSSFWorkbook(fs);
                }
                else
                {
                    wk = new XSSFWorkbook(fs);
                }
            }
            return wk;
        }
    }
}
